import { ExportOutlined, FullscreenExitOutlined, FullscreenOutlined } from '@ant-design/icons'
import { Button, Flex, DatePicker, Card, Typography, Table, Progress, Spin, Empty, message } from 'antd'
import React, { useEffect, useState } from 'react'
import iconred from '@/assets/images/enterprise/icon_red@2x.png'
import './index.scss'
import { useSearchParams } from 'react-router-dom'
import { capitalriskAPI, exportgenerateAPI } from '@/apis'
import axios from 'axios'
import dayjs from 'dayjs'
import WordcloudChart from '@/components/WordcloudChart'
import { toggleFull } from '@/utils'
const { Paragraph, Title, Text } = Typography
const { RangePicker } = DatePicker
const columns = [
    // {
    //     title: '序号',
    //     dataIndex: 'xuhao',
    //     key: 'xuhao',
    //     align: "center"
    // },
    {
        title: '风险类型',
        dataIndex: 'TYPE',
        key: 'TYPE',
    },
    {
        title: '笔数',
        dataIndex: 'COUNT',
        key: 'COUNT',
        align: "right"
    },
    {
        title: '金额(万元)',
        dataIndex: 'FKJE',
        key: 'FKJE',
        align: "right",
        render: (dom, rowData, index) => {
            return rowData.FKJE ? rowData.FKJE.toLocaleString() : 0
        }
    },
    // {
    //     title: '占比',
    //     dataIndex: 'zhanbi',
    //     key: 'zhanbi',
    //     align: "right",
    //     render: (text) => <Progress size={[200, 12]} status='normal' strokeLinecap="square" format={(percent) => `${percent}%`} strokeColor="#f93920" percent={text} percentPosition={{
    //         align: 'start',
    //         type: 'outer',
    //     }} />
    // },
    {
        title: '操作',
        dataIndex: 'caozuo',
        key: 'caozuo',
        render: (text) => <a>详情</a>,
        align: "center"
    }
];
// const data = [
//     {
//         key: '1',
//         xuhao: 1,
//         leixing: '空转走单',
//         bishu: 32,
//         jine: '500.00',
//         zhanbi: 42.7,
//     },
//     {
//         key: '2',
//         xuhao: 2,
//         leixing: '空转走单',
//         bishu: 110,
//         jine: '500.00',
//         zhanbi: 100,
//     },
//     {
//         key: '3',
//         xuhao: 3,
//         leixing: '空转走单',
//         bishu: 110,
//         jine: '500.00',
//         zhanbi: 90.7,
//     }
// ];
export default function Zijinfengxian({ data }) {
    const [isFullScreen, setIsFullScreen] = useState(false);
    const [chartBoxHeight, setChartBoxHeight] = useState(360)
    const [params] = useSearchParams()
    const company = params.get('company')
    // const [startDate, setStartDate] = useState(dayjs().startOf('year').format('YYYY-MM-DD'))
    // const [endDate, setEndDate] = useState(dayjs(new Date()).format('YYYY-MM-DD'))
    // const [startDate, setStartDate] = useState('2024-01-01')
    // const [endDate, setEndDate] = useState('2024-12-31')
    const [year, setYear] = useState(String(dayjs().year()))
    const [riskdata, setRiskdata] = useState({ details_total: [], risk_total: {} })
    const [isloading, setisloading] = useState(false)
    const [messageApi, contextHolder] = message.useMessage();
    const handleDate = (time) => {
        // setStartDate(dayjs(time[0]).format('YYYY-MM-DD'))
        // setEndDate(dayjs(time[1]).format('YYYY-MM-DD'))
        if (time) {
            setYear(dayjs(time).format('YYYY'));
        } else {
            setYear(String(dayjs().year()));
        }
    }
    useEffect(() => {
        const handleKeyDown = () => {
            // 全屏
            if (document.fullscreenElement) {
                setIsFullScreen(true);
                setChartBoxHeight('100%')
            } else {
                setIsFullScreen(false);
                setChartBoxHeight(360)
            }
        };
        document.addEventListener('fullscreenchange', handleKeyDown);
    }, [])
    useEffect(() => {
        let is_cydw = data.company_info[0].IS_CYDW
        function getData() {
            setisloading(true)
            capitalriskAPI({
                company,
                is_cydw,
                year
            }).then(res => {
                setRiskdata(res.data)
                setisloading(false)
            })
        }
        getData()
    }, [company, year, data])
    const report_download = () => {
        // setFlowLoading(true)
        // 生成报告
        exportgenerateAPI({
            company: data.company_info[0].GSMC,
        }).then(res => {
            if (res.code == 200) {
                messageApi.open({
                    type: 'success',
                    content: res.message,
                });
                axios.get(`http://192.168.1.188:9000/kshx/download-reportfile?uuid=${res.data}`, {
                    responseType: 'blob', 
                    headers: {
                        Authorization: 'Bearer ' + localStorage.getItem('kshxtoken')
                    }
                }).then(res => {
                    const blob = new Blob([res.data], { type: res.headers['content-type'] });
                    let fileName = data.company_info[0].GSMC + '.docx'; // 默认名
                    // 创建下载链接并触发下载
                    const url = window.URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.href = url;
                    a.download = fileName;
                    document.body.appendChild(a);
                    a.click();
                    a.remove();
                    window.URL.revokeObjectURL(url);
                }).catch(err => {
                    console.error('文件下载失败:', err);
                });
            }else{
                messageApi.open({
                    type: 'error',
                    content: res.message,
                });
            }
        }).catch(()=>{
            messageApi.open({
                type: 'error',
                content: '报告生成失败！',
            });
        }).finally(() => {
            // setFlowLoading(false)
        })
    }
    return (
        <Spin tip="页面加载中..." spinning={isloading} size='large'>
            <div className='rival-container risk-container'>
                <Flex justify='center' className='title'>
                    <Title level={3}>{company}</Title>
                    {contextHolder}
                    <Button className='btn' type='link' icon={<ExportOutlined />} onClick={report_download}>导出报告</Button>
                </Flex>
                <Flex justify='center' style={{ marginTop: '14px' }}>
                    {/* <RangePicker onChange={handleDate} defaultValue={[dayjs(startDate, 'YYYY-MM-DD'), dayjs(endDate, 'YYYY-MM-DD')]}></RangePicker> */}
                    <DatePicker onChange={handleDate} defaultValue={dayjs(year, 'YYYY')} picker="year" />
                </Flex>
                <Card className='indicator-wrap'>
                    <Flex align='center'>
                        <img src={iconred} style={{ width: '22px', marginRight: '8px' }} alt='' />
                        <Title level={5}>司库风险监测</Title>
                    </Flex>
                    <Paragraph className='desc'>涉及司库风险监测  <Text strong>{riskdata.risk_total.type}</Text> 种， 笔数总计 <Text strong>{riskdata.risk_total.count}</Text>笔， 金额总计 <Text strong>{riskdata.risk_total.amount ? (riskdata.risk_total.amount ? riskdata.risk_total.amount.toLocaleString() : 0) : 0}</Text> 万元</Paragraph>
                </Card>
                <Table style={{ marginTop: 20 }} columns={columns} size='small' dataSource={riskdata.details_total} pagination={false} rowKey="TYPE"/>
                <Flex vertical gap={16}>
                    <Flex style={{ marginTop: '24px' }} justify='space-between'>
                        <Title level={5}>风险标签</Title>
                    </Flex>
                    <div className="tags-container tags-container4">
                        <Flex className="title" justify="space-between" align="center">
                            <p>{data.company_info[0] && data.company_info[0].GSMC}</p>
                            <Button onClick={() => toggleFull('.tags-container4')} size="small" color="primary"
                                variant="text" icon={isFullScreen ? <FullscreenExitOutlined /> : <FullscreenOutlined />}>{isFullScreen ? '退出全屏' : '全屏查看'}</Button>
                        </Flex>
                        <Flex vertical justify="center" className="chart-box" style={{ width: '100%', height: chartBoxHeight }}>
                            {riskdata.details_total && riskdata.details_total.length !== 0 ? <WordcloudChart data={riskdata.details_total.map(item => ({
                                name: item.TYPE,
                                value: Math.floor(item.FKJE)
                            }))} /> : <Empty description='暂无数据' image={Empty.PRESENTED_IMAGE_SIMPLE}></Empty>}
                        </Flex>
                    </div>
                </Flex>
            </div>
        </Spin>
    )
}
